package xj.util.gui;

import java.awt.Image;
import java.net.URL;

import javax.swing.ImageIcon;

public class ResourceLoader {

  /**
   * Fixes a platform dependent filename to standard URI form.
   * 
   * @param str
   *                The string to fix.
   * 
   * @return Returns the fixed URI string.
   */
  public static final String filenameToURI(String str) {
    // handle platform dependent strings
    str = str.replace(java.io.File.separatorChar, '/');
    // Windows fix
    if (str.length() >= 2) {
      if (str.charAt(1) == ':') {
	char ch0 = Character.toUpperCase(str.charAt(0));
	if (ch0 >= 'A' && ch0 <= 'Z') {
	  str = "/" + str;
	}
      }
    }
    return str;
  }

  public static URL getResourceURI(String resourceName) {
    if (resourceName != null) {
      return ResourceLoader.class.getResource(resourceName);
    }
    return null;
  }

  public static ImageIcon loadIconResource(String imgName) {
    return loadIconResource(imgName, imgName);
  }

  public static ImageIcon loadIconResource(String imgName, String desc) {
    try {
      URL imgURL = ResourceLoader.class.getResource(imageName(imgName));
      if (imgURL == null) {
	imgURL = new URL(imgName + ".gif");
      }
      return new ImageIcon(imgURL, desc + " ");
    } catch (Exception ex) {
      if (debug) {
	System.out.println("Exception in loadIconResource: " + ex.getMessage());
      }
      return new ImageIcon(desc);
    }
  }

  public static Image loadImage(String imgName) {
    ImageIcon icon = loadIconResource(imgName);
    if (icon != null) {
      return icon.getImage();
    }
    return null;
  }

  public static void setIconDir(String dir) {
    iconDir = dir;
  }

  public static String getIconDir() {
    return iconDir;
  }

  protected static String imageName(String name) {
    return iconDir + name + ".gif";
  }

  protected static String iconDir = "/icons/";

  protected static final boolean debug = true;

}
